package org.ii.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Element;
import org.ii.dataprovider.dapper.Dapp;
import org.ii.dataprovider.dapper.corporatecritic.SearchCorporateCriticByCompanyNameDapperService;
import org.ii.domain.company.CorporateCriticCompany;

public class SearchCorporateCriticByCompanyNameDapperServiceImpl implements SearchCorporateCriticByCompanyNameDapperService {
	
	protected Dapp dapp;
	protected String DAPP_NAME = "ii42org_corporateCritic_namesearch";
	protected String DAPP_ROOT_ELEMENT = "corporateCriticCompany";

	@Override
	public List<CorporateCriticCompany> searchCorporateCriticByCompanyName(
		String companyName) throws Exception {
		
		List<CorporateCriticCompany> companies = new ArrayList<CorporateCriticCompany>();
		dapp = new Dapp(DAPP_NAME, new String[]{companyName});
		companies = getSetOfCorporateCriticCompaniesFromDappResult(dapp);
		return companies;
	}
	
	@SuppressWarnings("unchecked")
	private List<CorporateCriticCompany> getSetOfCorporateCriticCompaniesFromDappResult(Dapp searchCorporateCriticByCompanyNameDappResults) throws Exception {
		List<CorporateCriticCompany> companies = new ArrayList<CorporateCriticCompany>();
		CorporateCriticCompany newCompany;
		Iterator<Element> searchResultsItr = dapp.getDOM().getRootElement().elementIterator(DAPP_ROOT_ELEMENT);
		while (searchResultsItr.hasNext()){
			newCompany = new CorporateCriticCompany();
			Element searchResults = searchResultsItr.next();
			newCompany.setName(searchResults.elementText("company"));
			newCompany.setEthiscore(searchResults.elementText("ethiscore"));
			companies.add(newCompany);
		}
		return companies;
	}

}
